<template>

  <!-- 商品管理页面 -->

  <Layout>
    <el-card class="box-card">
      <div style="display: flex;justify-content: center;flex-direction: column;align-items: center;">
        <h2 style="display: flex;justify-content: flex-start;padding-left: 10px;">用户管理</h2>
        <div style="width: 100%;margin-top: 10px;">
          <el-form :model="queryForm" :inline="true" label-width="60px">
            <el-form-item label="昵称">
              <el-input v-model="queryForm.nickname" placeholder="请输入名称" size="small" clearable=""></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" plain size="mini" @click="handleSs()">查询</el-button>
              <!--              <el-button type="info" plain size="mini" @click="handleCz()">重置</el-button>-->
              <el-button type="info" plain size="mini" @click="handleEdit()">新增</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="springList" style="width: 100%" v-loading="loading" element-loading-text="拼命加载中"
                    element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.4)">
            <el-table-column label="ID" prop="id" width="50px"></el-table-column>
            <el-table-column label="昵称" prop="nickname" align="center" width="200px"></el-table-column>
            <el-table-column label="头像" prop="avtar" align="center" width="100%">
              <template slot-scope="scope">
                <el-image style="width: 100px; height: 50px" :src="scope.row.avtar" fit="cover">
                </el-image>
              </template>
            </el-table-column>
            <el-table-column label="用户名" prop="username" align="center" width="210px"></el-table-column>
            <el-table-column label="密码" prop="password" align="center">
            </el-table-column>
            <el-table-column label="邮箱" prop="email" align="center"></el-table-column>
            <el-table-column label="手机" prop="phone" align="center"></el-table-column>
            <el-table-column label="年龄" prop="age" align="center"></el-table-column>
            <el-table-column label="性别" prop="sex" align="center" width="100%">
              <template slot-scope="scope">
                <div v-if="scope.row.sex==0">未知</div>
                <div v-if="scope.row.sex==1">男</div>
                <div v-if="scope.row.sex==2">女</div>
              </template>
            </el-table-column>
            <el-table-column label="注册时间" prop="register_time" align="center"
                             width="160px">
              <template slot-scope="scope">
                <div>{{ getTime(scope.row.register_time) }}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="text" size="mini" style="color: orange;" @click="handleEdit(scope.row)"
                           icon="el-icon-edit">
                  编辑
                </el-button>
                <el-button type="text" size="mini" style="color: red;" @click="handleDel(scope.row.id)"
                           icon="el-icon-delete">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- current-page.sync当前页数 -->
        <!-- total总条目数 -->
        <!-- page-size显示条数 -->
        <!-- layout	组件布局，子组件名用逗号分隔 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                       :current-page="queryForm.page" :page-size="queryForm.limit"
                       layout="total, sizes, prev, pager, next, jumper" :total="total" style="padding: 20px 0;">
        </el-pagination>

      </div>

    </el-card>

    <!--    修改用户信息部分-->
    <el-dialog :visible.sync="showDialog" :title="isAdd?'新增用户':'编辑用户'" @close="showDialog = false">
      <el-form :model="form" :inline="true" label-width="60px">
        <el-form-item label="用户名">
          <el-input v-model="form.username" placeholder="请输入名称" :disabled="!isAdd"></el-input>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="form.nickname" placeholder="请输入名称" clearable=""></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" clearable=""></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="form.email" placeholder="请输入邮箱" clearable=""></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="form.phone" placeholder="请输入手机号" clearable=""></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio v-model="form.sex" label="0">未知</el-radio>
          <el-radio v-model="form.sex" label="1">男</el-radio>
          <el-radio v-model="form.sex" label="2">女</el-radio>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="form.age" placeholder="请输入年龄" clearable=""></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
                  class="avtar-uploader"
                  :action="updateUrl"
                  :headers="header"
                  :data="updateData"
                  :show-file-list="false"
                  :on-success="handleavtarSuccess">
            <img v-if="form.avtar" :src="form.avtar" class="avtar">
            <i v-else class="el-icon-plus avtar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>

      <el-button type="primary" @click="submit()">确认</el-button>
    </el-dialog>
  </Layout>
</template>

<script>
  // import axios from 'axios';
  import {weChatTimeFormat} from '@/utils/time'

  export default {
    data() {
      return {
        // 商品列表
        springList: [],
        token: "",
        total: 0,
        queryForm: {
          page: 1,
          limit: 10,
          nickname: ''
        },
        form: {},
        loading: false,
        showDialog: false,
        header: {
          "token": localStorage.getItem("Admin-Token")
        },
        updateData: {
          type: 1 //表示上传的是头像
        },
        updateUrl: process.env.VUE_APP_BASE_API + "/uploadFile",
        isAdd:false//false是编辑，true是新增
      };
    },
    created() {
      this.getList()
    },
    methods: {
      getTime(time) {
        return weChatTimeFormat(time)
      },
      getList() {
        this.loading = true
        this.token = localStorage.getItem('Admin-Token');
        this.$axios.get('/admin/user/list',
                {
                  params: this.queryForm
                }
        ).then(res => {
          this.springList = res.data.data.list
          for (const springListElement of this.springList) {
            springListElement.sex = springListElement.sex + ""
          }

          this.total = res.data.data.total
          // this.loading = false
          // console.log(this.springList)
          console.log(res.data)
        })
                .catch(e => {
                  console.log(e)
                })
                .finally(() => {
                  this.loading = false
                  console.log(this.loading, "111")
                })
      },
      //分页

      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        // this.queryForm.pageNum=1;
        this.queryForm.limit = val;
        this.getList()
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.queryForm.page = val;
        this.getList()
      },
      // 删除商品列表
      handleDel(id) {
        this.$confirm('确定删除ID为：' + id + '的用户吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // this.$axios({
          //   url:"/admin/user/delete",
          //   methods: "post",
          //   data:{id: id}
          // }
          // )
          // 删除选择的数据
          this.$axios.post("/admin/user/delete",{id: id}
          ).then((res) => {
            // location.reload(); // 刷新页面
            if (res.data.code == 0) {
              this.getList();
              this.$message({
                message: '删除成功',
                type: 'success'
              });
            } else {
              this.$message({
                message: res.data.msg,
                type: 'warning'
              });
            }


          })
                  .catch((res) => {
                    this.$message({
                      type: 'info',
                      message: '已取消删除'
                    });
                    console.log("删除", id)

                  })
        }).catch((res) => {
        })
      },

      // 搜索按钮
      handleSs() {
        this.queryForm.page = 1;
        this.getList();
      },
      // 重置按钮
      handleCz() {
        this.queryForm = {
          page: 1,
          limit: 10
        }
        this.handleSs()
      },
      //点击编辑按钮
      handleEdit(row) {
        if(row){//编辑
          this.isAdd = false
          this.form = JSON.parse(JSON.stringify(row))//重新生成个对象，避免修改数据会直接修改列表
          this.showDialog = true//显示对话框
        }else{//新增
          this.form ={
            id:0,
            username:'',
            password:'',
            sex:0,
            phone:"",
            email:'',
            avtar:'',
            nickname:''
          }
          this.isAdd = true
          this.showDialog = true//显示对话框
        }

      },
      //处理头像上传成功
      handleavtarSuccess(res, file) {
        this.form.avtar = res.data;
      },
      //提交编辑
      submit() {

        this.$axios.post("/admin/updateUserInfo", this.form).then(res => {

          if (res.data.code == 0) {
            this.getList()
            this.$message({
              message: res.data.msg,
              type: 'success'
            });
            this.showDialog = false //隐藏对话框
          } else {
            this.$message({
              message: res.data.msg,
              type: 'warning'
            });
          }
        })
        // this.$axios({
        //   methods:"post",
        //   url:"/admin/updateUserInfo",
        //   data:this.form
        // }).then(res=>{
        //   if(res.data.code==0){
        //     this.getList()
        //     this.$message({
        //       message: '修改成功',
        //       type: 'success'
        //     });
        //   }else{
        //     this.$message({
        //       message: res.data.msg,
        //       type: 'warning'
        //     });
        //   }
        // })
      }
    }
  }
</script>
<style>
  * {
    margin: 0;
    padding: 0;
  }

  .avtar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avtar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avtar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avtar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>